﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;

namespace ManageTicket.Partner
{
    public partial class frmPartnerLabourContract : frmBase
    {
        #region Contructor
        public frmPartnerLabourContract()
        {
            InitializeComponent();
        }
        #endregion

        #region Variable
        ManageTicket.Library.Control.ExecuteControl exeCtrl;

        //permission
        bool bAdd = false;
        bool bEdit = false;
        bool bDelete = false;
        bool bCancel = false;
        bool bSave = false;
        bool bFunction = false;
        bool bView = false;
        bool bFind = false;
        bool bExport = false;
        bool bSendmail = false;
        bool bPrint = false;

        clsMethod4All objMethod = new clsMethod4All();
        ManageTicket.Library.Common.CommonFunction clsCommonFunc = new ManageTicket.Library.Common.CommonFunction();
        private Business.Customer boCustomer = new Business.Customer();
        private Business.Provider boProvider = new Business.Provider();
        private Business.PartnerLabourContract boPLC = new Business.PartnerLabourContract();
        private Business.Employee boEmployee = new Business.Employee();
        #endregion

        #region Event
        private void frmPartnerLabourContract_Load(object sender, EventArgs e)
        {
            //execute control
            exeCtrl = new ManageTicket.Library.Control.ExecuteControl();
            exeCtrl.Dock = DockStyle.Fill;
            exeCtrl.lblDescription.Text = "Cập nhật hợp đồng";
            pnlExe.Controls.Add(exeCtrl);

            //permission
            clsCommonFunc.GetPermission(ref bAdd, ref bEdit, ref bDelete, ref bCancel, ref bSave, ref bFunction, ref bView, ref bFind, ref bExport, ref bSendmail, ref bPrint, frmMain.CurrentUser.UserId, "FORM_07");

            LoadStatusOnce();
            LoadStatus(false, false, false, false);
        }

        private void txtSearchCustomer_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                ArrayList arrResult = new ArrayList();
                if (objMethod.IsInteger(txtSearchCustomer.Text))
                {
                    DataObjects.Customer oCus = boCustomer.GetObjectByPK(txtSearchCustomer.Text);
                    if (oCus != null)
                    {
                        arrResult.Add(oCus);
                    }
                }
                else
                {
                    ArrayList arr1 = boCustomer.GetListQuickSearch(txtSearchCustomer.Text);
                    if (arr1 != null)
                    {
                        if (arr1.Count == 1)
                        {
                            arrResult.Add(arr1[0]);
                        }
                        else if (arr1.Count > 1)
                        {
                            frmQuickSearchCustomer frmQS = new frmQuickSearchCustomer(arr1);
                            frmQS.ShowDialog();
                            foreach (DataObjects.Customer oCus in frmQS.arrResult)
                            {
                                arrResult.Add(oCus);
                            }
                        }
                    }
                }

                ListViewItem item;
                int firstItem = 0;
                foreach (DataObjects.Customer oCus in arrResult)
                {
                    if (!IsInListView(oCus.CustomerId, lvwCustomer))
                    {
                        item = new ListViewItem();
                        item.Text = oCus.CustomerId;
                        item.SubItems.Add(oCus.CustomerName);
                        lvwCustomer.Items.Add(item);
                        if (firstItem == 0)
                        {
                            item.Selected = true;
                        }
                        firstItem++;
                    }
                }
            }
        }

        private void lvwCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvwCustomer.SelectedItems.Count > 0)
            {
                GetListContract(lvwCustomer.SelectedItems[0].Text);
            }
            else
            {
                lvwLabourContract.Items.Clear();
                lvwLabourContract_SelectedIndexChanged(null, null);
            }
        }

        private void txtSearchProvider_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                ArrayList arrResult = new ArrayList();
                if (objMethod.IsInteger(txtSearchProvider.Text))
                {
                    DataObjects.Provider oPro = boProvider.GetObjectByPK(txtSearchProvider.Text);
                    if (oPro != null)
                    {
                        arrResult.Add(oPro);
                    }
                }
                else
                {
                    ArrayList arr1 = boProvider.GetListQuickSearch(txtSearchProvider.Text);
                    if (arr1 != null)
                    {
                        if (arr1.Count == 1)
                        {
                            arrResult.Add(arr1[0]);
                        }
                        else if (arr1.Count > 1)
                        {
                            frmQuickSearchProvider frmQS = new frmQuickSearchProvider(arr1);
                            frmQS.ShowDialog();
                            foreach (DataObjects.Provider oPro in frmQS.arrResult)
                            {
                                arrResult.Add(oPro);
                            }
                        }
                    }
                }

                ListViewItem item;
                int firstItem = 0;
                foreach (DataObjects.Provider oPro in arrResult)
                {
                    if (!IsInListView(oPro.ProviderId, lvwProvider))
                    {
                        item = new ListViewItem();
                        item.Text = oPro.ProviderId;
                        item.SubItems.Add(oPro.ProviderName);
                        lvwProvider.Items.Add(item);
                        if (firstItem == 0)
                        {
                            item.Selected = true;
                        }
                        firstItem++;
                    }
                }
            }
        }

        private void lvwProvider_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvwProvider.SelectedItems.Count > 0)
            {
                GetListContract(lvwProvider.SelectedItems[0].Text);
            }
            else
            {
                lvwLabourContract.Items.Clear();
                lvwLabourContract_SelectedIndexChanged(null, null);
            }
        }

        private void lvwLabourContract_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvwLabourContract.SelectedItems.Count > 0)
            {
                FillData(lvwLabourContract.SelectedItems[0].Text);
                LoadStatus(true, true, false, true);
            }
            else
            {
                Cancel();
            }
        }

        private void txtMonths_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtMonths.Text);
        }

        private void txtDiscountCommon_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtDiscount.Text);
        }

        private void txtMaxDept_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtMaxDept.Text);
        }

        private void txtMaxDept_Leave(object sender, EventArgs e)
        {
            txtMaxDept.Text = objMethod.FormatCurency(txtMaxDept.Text);
        }

        private void txtEmployeeId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtEmployeeId.Text);
                if (oCus != null)
                {
                    txtFullName.Text = oCus.LastName + " " + oCus.FirstName;
                    txtFullName.Focus();
                }
            }
        }

        private void txtMonths_TextChanged(object sender, EventArgs e)
        {
            CalcEndDate();
        }

        private void dtpEffectiveDate_ValueChanged(object sender, EventArgs e)
        {
            CalcEndDate();
        }
        #endregion

        #region Execute
        public override void Add()
        {
            txtContractNo.Text = "";
            txtContractNo.ReadOnly = false;
            objMethod.ClearText(new Control[] { txtContractNo, txtMonths, txtDiscount, txtMaxDept, txtPartnerId, txtPartnerName, txtPersonRepresent, txtEmployeeId, txtFullName, txtDocumentPath, txtRemark });
            if (tabCustomer.IsSelected)
            {
                if (lvwCustomer.SelectedItems.Count > 0)
                {
                    DataObjects.Customer oCus = boCustomer.GetObjectByPK(lvwCustomer.SelectedItems[0].Text);
                    if (oCus != null)
                    {
                        txtPartnerId.Text = oCus.CustomerId;
                        txtPartnerName.Text = oCus.CustomerName;
                        txtPersonRepresent.Text = oCus.PersonRepresent;
                    }
                }
            }
            else if (tabProvider.IsSelected)
            {
                if (lvwProvider.SelectedItems.Count > 0)
                {
                    DataObjects.Provider oCus = boProvider.GetObjectByPK(lvwProvider.SelectedItems[0].Text);
                    if (oCus != null)
                    {
                        txtPartnerId.Text = oCus.ProviderId;
                        txtPartnerName.Text = oCus.ProviderName;
                        txtPersonRepresent.Text = oCus.PersonRepresent;
                    }
                }
            }
            LoadStatus(false, false, true, true);
            txtContractNo.Focus();
        }

        public override void Delete()
        {
            try
            {
                if (txtContractNo.Text == "")
                    return;

                if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Aquarius", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //Check Existing in table
                    //if (this.CheckExitToDelete(oDept.DEPT_CODE)) {
                    //    MessageBox.Show(".", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    return;
                    //}

                    //delete
                    boPLC.DeleteByPK(txtContractNo.Text);
                    RemoveItem(txtContractNo.Text);
                    MessageBox.Show("Xóa hợp đồng thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Cancel();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void Cancel()
        {
            objMethod.ClearText(new Control[] { txtContractNo, txtMonths, txtDiscount, txtMaxDept, txtPartnerId, txtPartnerName, txtPersonRepresent, txtEmployeeId, txtFullName, txtDocumentPath, txtRemark });
            if (lvwLabourContract.Items.Count > 0)
            {
                lvwLabourContract.Items[0].Selected = true;
            }
            else
            {
                LoadStatus(true, false, false, false);
            }
        }

        public override void Save()
        {
            if (txtContractNo.Text == "")
            {
                return;
            }
            if (CheckValid())
            {
                try
                {
                    DataObjects.PartnerLabourContract oPLC = new DataObjects.PartnerLabourContract();
                    oPLC.ContractNo = txtContractNo.Text;
                    oPLC.Months = txtMonths.Text != "" ? int.Parse(txtMonths.Text) : 0;
                    oPLC.EffectiveDate = dtpEffectiveDate.Value.Date;
                    oPLC.EndDate = dtpEndDate.Value.Date;
                    oPLC.SignDate = dtpSignDate.Value.Date;
                    oPLC.Discount = txtDiscount.Text != "" ? double.Parse(txtDiscount.Text) : 0;
                    oPLC.MaxDept = txtMaxDept.Text != "" ? double.Parse(txtMaxDept.Text) : 0;
                    oPLC.PartnerId = txtPartnerId.Text;
                    oPLC.PersonRepresent = txtPersonRepresent.Text;
                    oPLC.EmployeeId = txtEmployeeId.Text;
                    oPLC.DocumentPath = txtDocumentPath.Text;
                    oPLC.Remark = txtRemark.Text;
                    if (tabCustomer.IsSelected)
                        oPLC.KindOfContract = "Customer";
                    else if (tabProvider.IsSelected)
                        oPLC.KindOfContract = "Provider";
                    oPLC.Status = "CUR";

                    if (txtContractNo.ReadOnly)
                    {
                        //update
                        boPLC.Update(oPLC);
                        RemoveItem(oPLC.ContractNo);
                        AddItem(oPLC);
                    }
                    else
                    {
                        //insert
                        if (CheckIsExist(oPLC.ContractNo))
                        {
                            MessageBox.Show("Mã hợp đồng đã tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtContractNo.Focus();
                            return;
                        }
                        boPLC.Insert(oPLC);
                        AddItem(oPLC);
                    }

                    txtContractNo.ReadOnly = true;
                    LoadStatus(true, true, false, true);
                    MessageBox.Show("Cập nhật hợp đồng thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Environment.NewLine + "Không thể cập nhật hợp đồng.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        #endregion

        #region Method
        private bool IsInListView(string id, ListView lvw)
        {
            foreach (ListViewItem item in lvw.Items)
            {
                if (item.Text == id)
                {
                    return true;
                }
            }
            return false;
        }

        private void GetListContract(string id)
        {
            lvwLabourContract.Items.Clear();
            ArrayList arr = boPLC.GetListByPartnerId(id);
            if (arr != null)
            {
                if (arr.Count > 0)
                {
                    
                    ListViewItem item;
                    foreach (DataObjects.PartnerLabourContract oPLC in arr)
                    {
                        item = new ListViewItem();
                        item.Text = oPLC.ContractNo;
                        item.SubItems.Add(oPLC.Months.ToString());
                        item.SubItems.Add(oPLC.EffectiveDate.Value.ToString("dd/MM/yyyy"));
                        item.SubItems.Add(oPLC.EndDate.Value.ToString("dd/MM/yyyy"));
                        item.SubItems.Add(oPLC.Discount.ToString());
                        item.SubItems.Add(objMethod.FormatCurency(oPLC.MaxDept.ToString()));
                        lvwLabourContract.Items.Add(item);
                    }
                }   
            }
            if (lvwLabourContract.Items.Count > 0)
            {
                lvwLabourContract.Items[0].Selected = true;
            }
        }

        private void FillData(string contract_no)
        {
            DataObjects.PartnerLabourContract oPLC = boPLC.GetObjectByPK(contract_no);
            if (oPLC != null)
            {
                txtContractNo.ReadOnly = true;
                txtContractNo.Text = oPLC.ContractNo;
                txtMonths.Text = oPLC.Months.ToString();
                dtpEffectiveDate.Value = oPLC.EffectiveDate.Value;
                dtpEndDate.Value = oPLC.EndDate.Value;
                dtpSignDate.Value = oPLC.SignDate.Value;
                txtDiscount.Text = oPLC.Discount.ToString();
                txtMaxDept.Text = objMethod.FormatCurency(oPLC.MaxDept.ToString());
                txtPartnerId.Text = oPLC.PartnerId;
                txtPersonRepresent.Text = oPLC.PersonRepresent;
                if (oPLC.KindOfContract == "Customer")
                {
                    DataObjects.Customer oCus = boCustomer.GetObjectByPK(oPLC.PartnerId);
                    if (oCus != null)
                    {
                        txtPartnerName.Text = oCus.CustomerName;
                    }
                }
                else if (oPLC.KindOfContract == "Provider")
                {
                    DataObjects.Provider oPro = boProvider.GetObjectByPK(oPLC.PartnerId);
                    if (oPro != null)
                    {
                        txtPartnerName.Text = oPro.ProviderName;
                    }
                }

                txtEmployeeId.Text = oPLC.EmployeeId;
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(oPLC.EmployeeId);
                if (oEmp != null)
                    txtFullName.Text = oEmp.LastName + " " + oEmp.FirstName;

                txtDocumentPath.Text = oPLC.DocumentPath;
                txtRemark.Text = oPLC.Remark;
            }
        }

        private void LoadStatusOnce()
        {
            exeCtrl.btnEdit.Enabled = false;
            exeCtrl.btnCancel.Enabled = false;
            exeCtrl.btnView.Enabled = false;
            exeCtrl.btnFunction.Enabled = false;
            exeCtrl.btnFind.Enabled = false;
            exeCtrl.btnExport.Enabled = false;
            exeCtrl.btnSendmail.Enabled = false;
            exeCtrl.btnPrint.Enabled = false;

            exeCtrl.btnEdit.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnView.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFunction.BackColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFind.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnExport.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnSendmail.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = Color.FromArgb(171, 171, 171);

            exeCtrl.btnEdit.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnView.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFunction.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFind.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnExport.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnSendmail.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnPrint.ForeColor = Color.FromArgb(241, 244, 251);
        }

        private void LoadStatus(bool blAdd, bool blDelete, bool blCancel, bool blSave)
        {
            exeCtrl.btnAdd.Enabled = blAdd & bAdd;
            exeCtrl.btnDelete.Enabled = blDelete & bDelete;
            exeCtrl.btnCancel.Enabled = blCancel & bCancel;
            exeCtrl.btnSave.Enabled = blSave & bSave;


            exeCtrl.btnAdd.ButtonColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnDelete.ButtonColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnSave.ButtonColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);

            exeCtrl.btnAdd.ForeColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnDelete.ForeColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnSave.ForeColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
        }

        private void AddItem(DataObjects.PartnerLabourContract oPLC)
        {
            ListViewItem item = new ListViewItem();
            item.Text = oPLC.ContractNo;
            item.SubItems.Add(oPLC.Months.ToString());
            item.SubItems.Add(oPLC.EffectiveDate.Value.ToString("dd/MM/yyyy"));
            item.SubItems.Add(oPLC.EndDate.Value.ToString("dd/MM/yyyy"));
            item.SubItems.Add(oPLC.Discount.ToString());
            item.SubItems.Add(objMethod.FormatCurency(oPLC.MaxDept.ToString()));
            lvwLabourContract.Items.Add(item);
        }

        private void RemoveItem(string Id)
        {
            foreach (ListViewItem item in lvwLabourContract.Items)
            {
                if (item.Text == Id)
                {
                    lvwLabourContract.Items.Remove(item);
                    return;
                }
            }
        }

        private bool CheckValid()
        {
            if (txtContractNo.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập số hợp đồng.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContractNo.Focus();
                return false;
            }
            else if (!objMethod.CheckSpecialCharacter(txtContractNo.Text))
            {
                MessageBox.Show("Số hợp đồng không được nhập các ký tự đặc biệt.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContractNo.Focus();
                return false;
            }

            if (txtMonths.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập thời hạn hợp đồng.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtMonths.Focus();
                return false;
            }

            if (txtPartnerId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn đối tác.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPartnerId.Focus();
                return false;
            }
            if (txtEmployeeId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn nhân viên.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmployeeId.Focus();
                return false;
            }
            else
            {
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtEmployeeId.Text);
                if (oEmp == null)
                {
                    MessageBox.Show("Nhân viên không tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmployeeId.Focus();
                    return false;
                }
            }

            return true;
        }

        private bool CheckIsExist(string id)
        {
            DataObjects.PartnerLabourContract oPLC = boPLC.GetObjectByPK(id);
            if (oPLC != null)
            {
                return true;
            }
            return false;
        }

        private void CalcEndDate()
        {
            int month = 0;
            if (txtMonths.Text != "")
                month = int.Parse(txtMonths.Text);
            dtpEndDate.Value = dtpEffectiveDate.Value.AddMonths(month);
        }
        #endregion        

        private void tabControl1_SelectedTabChanged(object sender, DevComponents.DotNetBar.TabStripTabChangedEventArgs e)
        {
            if (tabCustomer.IsSelected)
            {
                if (lvwCustomer.Items.Count > 0)
                {
                    lvwCustomer.Items[0].Selected = true;
                }
                else
                {
                    lvwLabourContract.Items.Clear();
                    lvwLabourContract_SelectedIndexChanged(null, null);
                }
            }
            else if (tabProvider.IsSelected)
            {
                if (lvwProvider.Items.Count > 0)
                {
                    lvwProvider.Items[0].Selected = true;
                }
                else
                {
                    lvwLabourContract.Items.Clear();
                    lvwLabourContract_SelectedIndexChanged(null, null);
                }
            }
        }
      
    }
}
